package week12.consumer;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import week12.test.TestActivemq;

import javax.jms.*;
import java.util.concurrent.atomic.LongAdder;

public class JMSConsumer {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static final String BROKEURL = TestActivemq.BROKEURL;

    public static Connection start(LongAdder adder, int threads) {

        // 连接
        Connection result = null;
        try {
            // 实例化连接工厂
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);
            // 通过连接工厂获取连接
            Connection connection = connectionFactory.createConnection();
            // 启动连接
            connection.start();
            result = connection;

            new Thread(() -> {

                try {

                    while (true) {
                        try {
                            // 获取Session
                            Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
                            // 创建消息队列，queue
                            Destination queueDestination = session.createQueue("week12.topic15");

                            MessageConsumer consumer = session.createConsumer(queueDestination);

                            while (true) {
                                //消费方式是死等receive()
                                consumer.receive();
                                adder.add(1);
                            }
                        } catch (Exception e) {
                            break;
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();

                }

            }).start();
        } catch (JMSException e) {
            e.printStackTrace();
        }
        return result;
    }


}
